$(document).ready(function(){
	
	// Case: deleting a credentials
	$('a.delete-credentials').click(function(){
		if ($('a.delete-credentials').length <= 1) {
			alert('On ne supprime pas le dernier rôle !');
			return false;
		}
		var e = $(this);
		$.ajax({
			type:	'POST',
			url:	'process/credentials_delete.php',
			data:	'id='+e.attr('href'),
			success: function(msg){
				if (msg != 'OK')
					alert(msg);
				else
					e.parent().parent().remove();
			}
		});
		return false;
	});
	
	// Case: creating a new credentials
	$('a#credentials-add').click(function(){
		$.ajax({
			type:	'POST',
			url:	'forms/credentials.php',
			success: function(msg) {
				var select = $('div#credentials_form');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Ajouter': function(){
							var name = $('input[name=credentials-name]'),
								checkboxes = $('input:checkbox'),
								data = 'name='+name.val();
							name.removeClass('ui-state-error');
							if (check_length(name, 'Nom', 1, 255)) {
								checkboxes.each(function(){
									data = data+'&'+$(this).val()+'=';
									if ($(this).is(':checked'))
										data = data+'1';
									else
										data = data+'0';
								});
								$.ajax({
									type:	'POST',
									url:	'process/credentials_add.php',
									data:	data,
									success: function(msg){
										$('#table-credentials tr:last').prev('tr').after(msg);
										$('a.delete-doc').button();
										select.dialog('close');
									}
								});
							}
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
		return false;
	});
});